const express = require("express");
const userService = require("../../services/userService");
const jwt = require("../../util/jwt");

const router = express.Router();

// 登录
router.post("/login", async (req, res) => {
  if (req.body.userId && req.body.userPwd) {
    const data = await userService.login(req.body);
    jwt.publish(res, undefined, { id: data.id });
    res.send({
      code: 200,
      msg: "成功",
      data: data,
    });
  } else {
    res.send({
      code: 200,
      msg: "参数不全",
    });
  }
});

// 注册
router.post("/register", async (req, res) => {
  if (req.body.userId && req.body.userPwd && req.body.nickName) {
    const data = await userService.addUser(req.body);
    res.send({
      code: 200,
      msg: "成功",
      data: data,
    });
  } else {
    res.send({
      code: 200,
      msg: "参数不全",
    });
  }
});

// 初始化
router.get("/whoami", async (req, res) => {
  if (req.id) {
    const data = await userService.findUser(req.id);
    res.send({
      code: 200,
      msg: "成功",
      data: data,
    });
  } else {
    res.send({
      code: 200,
      msg: "参数不全",
    });
  }
});

module.exports = router;
